import { defineStore } from "pinia";
import { ref } from "vue";
import type { User } from ".";

export const useUserStore = defineStore(
  "user",
  () => {
    const token = ref<string | null>(null);
    const user = ref<User | null>(null);

    // 设置用户信息和token
    function login(userData: User, accessToken: string) {
      user.value = userData;
      token.value = accessToken;
    }

    // 更新用户信息
    function update(userData: User) {
      user.value = userData;
    }

    // 清除用户信息
    function logout() {
      user.value = null;
      token.value = null;
    }

    // 检查是否已登录
    function isLogin() {
      return user.value !== null;
    }

    return {
      token,
      user,
      login,
      update,
      logout,
      isLogin,
    };
  },
  {
    // 启用状态持久化
    persist: {
      storage: sessionStorage,
    },
  }
);
